import _ from "lodash";
import { ICmpnt } from "xcore/cmpnt"

export default {

    parsePathValue(obj: any, pathPrefix: string = ''): any {
        const result: any = {};
        for (const key in obj) {
            if (!["bind", "__themes"].includes(key) && obj.hasOwnProperty(key)) {
                const value = obj[key];
                const newPath = pathPrefix ? `${pathPrefix}.${key}` : key;
                if (Array.isArray(value)) {
                    result[newPath] = Array.from(value)
                } else if (value !== null && typeof value === 'object') {
                    Object.assign(result, this.parsePathValue(value, newPath));
                } else {
                    result[newPath] = value;
                }
            }
        }
        return result;
    },
    list(cmpnt: ICmpnt): any[] {
        let themesStr = localStorage.getItem(`ctl:theme:${cmpnt.ctl.name}`) || "[]";
        let themes = JSON.parse(themesStr);
        return themes;
    },

    save(cmpnt: ICmpnt, themeName: string): any {
        let props = this.parsePathValue(cmpnt.props)
        let theme = { name: themeName, props: props }
        this.append(cmpnt, theme);
        return theme;

    },
    append(cmpnt: ICmpnt, theme: any) {
        let themes = this.list(cmpnt);
        themes = themes.filter((t: any) => t.name != theme.name);
        themes.push(theme);
        localStorage.setItem(`ctl:theme:${cmpnt.ctl.name}`, JSON.stringify(themes));
    },

    apply(cmpnt: ICmpnt, themeName: string) {
        let themes = this.list(cmpnt);
        let theme = themes.find((t: any) => t.name == themeName);
        if (theme) {
            _.forEach(theme.props, (v: any, key: string) => {
                if (_.has(cmpnt.props, key)) {
                    _.set(cmpnt.props, key, v)
                }
            });
        }

    },
    delete(cmpnt: ICmpnt, themeName: string) {
        let themes = this.list(cmpnt);
        themes = themes.filter((t: any) => t.name != themeName);
        localStorage.setItem(`ctl:theme:${cmpnt.ctl.name}`, JSON.stringify(themes));
    },

} 